package com.mfcxy.admin.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mfcxy.entity.Type;
import com.mfcxy.exception.CustomException;
import com.mfcxy.service.ITypeService;
import com.mfcxy.tools.BackJson;

/**
 * 分類控制器
 * @author mfcxy
 *
 */
@Controller
@RequestMapping("/admin/type/")
public class TypeController {
	
	@Autowired
	private ITypeService typeService;
	
	/**
	 * 分类列表
	 * @param p
	 * @return
	 */
	@RequestMapping("list/{p}/{id}")
	public String list(@PathVariable("p") int p , @PathVariable("id") int id , Model model) {
		model.addAttribute("typemap", typeService.selctList(p , id));
		return "admin/type_list";
	}
	
	/**
	 * 新增视图
	 * @return
	 */
	@RequestMapping("addview")
	public String addView(Model model) {
		//查询一级分类
		model.addAttribute("onetype", typeService.listById(0));
		return "admin/type_add";
	}
	
	/**
	 * 根据分类id查询子分类
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("findchildrentype")
	public BackJson findChildrenType(@RequestParam("id") int id) {
		List<Type> typelist = typeService.listById(id);
		Map<String, Object> map = new HashMap<>();
		map.put("list", typelist);
		BackJson bj = new BackJson();
		bj.setCode(1);
		bj.setData(map);
		
		return bj;
	}
	
	/**
	 * 新增提交
	 * @param type
	 * @return
	 * @throws CustomException 
	 */
	@RequestMapping(value = "add" , method=RequestMethod.POST)
	public String add(@ModelAttribute Type type) throws CustomException {
		type.checkAdd();
		typeService.save(type);
		return "redirect:/admin/type/list/1/0";
	}
	
	
	
	
}